<script lang="ts" setup>
import router from "@/router";
import { login } from "@/api/api"
import { reactive, ref } from "vue";
import type {FormInstance, FormRules} from 'element-plus'
import {success} from "@/message/success";
import axios from "axios";
import {BASE_URL_PEPAY} from "@/api/config";
const time = ref(10)
const img = ref('')
const flag = ref(false)
const loading = ref(false)
const loginFlag = ref(false)
const text = ref("秒后获取")
const userData = reactive({
  username: "1213124214",
  password: "000",
  code:'1234'
})

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else {
    if (userData.username !== '') {
      if (!formRef.value) return
      formRef.value.validateField('checkPass')
    }
    callback()
  }
}
const password = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value !== userData.password) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}

const code = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof userData>>({
  username: [{ validator: validatePass, trigger: 'blur' }],
  password: [{ validator: password, trigger: 'blur' }],
  code: [{ validator:code, trigger: 'blur' }],
})

const formRef = ref<FormInstance>()

async function loginAdmin() {
  try {
    await login(userData);
    router.replace('/home');
  } catch (error) {
  }
}
function generateSecureRandomString(length = 16) {
  const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  const randomValues = new Uint32Array(length);

  window.crypto.getRandomValues(randomValues);

  for (let i = 0; i < 50; i++) {
    result += charset[randomValues[i] % charset.length];
  }

  const cs = {
    iv:'1324124',
    data: result
  }
  return cs;
}
// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true

      const encryptedData = await encryptData(generateSecureRandomString());
      const encryptedDataLgin = await encryptData(userData);
      // loginAdmin();
      setTimeout(() => {
        success("登陆成功");
        localStorage.setItem("authToken", encryptedData.data);
        localStorage.setItem("uid", encryptedDataLgin.data);
        router.replace('/home');
      }, 2000)
    } else {
      console.log('error submit!')
    }
  })
}
function refreshCaptcha(){
  // success("验证码");

  axios.get(`${BASE_URL_PEPAY}` +'/cs/code').then((res) =>{
    img.value = res.data.image;
    userData.code = res.data.code
  })
}
function getCode() {
  success("验证码获取成功");
  flag.value = !flag.value;
  loginFlag.value = !loginFlag.value;
  const mm = setInterval(() =>{
    time.value --;
    if (time.value === 0){
      clearInterval(mm);
      flag.value = !flag.value;
      time.value = 10;
    }
  },1000)
}

// 模拟从后端获取的密钥（实际应通过安全通道获取）
const rawKey = new Uint8Array([
  1, 22, 38, 14, 55, 62, 70, 81, 99, 10, 111, 122, 133, 144, 155, 166,
  177, 188, 199, 200, 211, 222, 233, 244, 255, 26, 27, 28, 29, 30, 31, 32
]);

let cryptoKey = null;

// 初始化密钥
async function initKey() {
  if (cryptoKey) return;
  try {
    cryptoKey = await crypto.subtle.importKey(
      'raw',
      rawKey,
      { name: 'AES-CBC' },
      false,
      ['encrypt', 'decrypt']
    );
  } catch (error) {
  }
}

// 加密数据
async function encryptData(data) {
  await initKey();
  try {
    const encoder = new TextEncoder();
    const dataBuffer = encoder.encode(JSON.stringify(data));

    // 生成随机IV（16字节）
    const iv = crypto.getRandomValues(new Uint8Array(16));

    const ciphertext = await crypto.subtle.encrypt(
      { name: 'AES-CBC', iv: iv },
      cryptoKey,
      dataBuffer
    );

    // 返回Base64编码的IV和密文
    return {
      iv: arrayBufferToBase64(iv),
      data: arrayBufferToBase64(ciphertext)
    };
  } catch (error) {
    throw error;
  }
}

// ArrayBuffer转换为Base64
function arrayBufferToBase64(buffer) {
  return btoa(String.fromCharCode(...new Uint8Array(buffer)));
}

refreshCaptcha()
</script>

<template>
  <div class="back-container">
    <div class="back-login-form">
      <img src="../../../assets/logo.jpg">
      <div class="form">
        <el-form @keyup.enter.down="submitForm(formRef)" status-icon ref="formRef" :rules="rules" style="width: 245px" :model="userData" label-width="auto" class="demo-dynamic">
          <el-form-item prop="username" label="" >
            <el-input type="text" placeholder="请输入账号" v-model="userData.username" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="password" label="">
            <el-input type="password" placeholder="请输入密码" show-password v-model="userData.password" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="code" label="">
            <div style="position: relative">
              <el-input type="text" style="width: 160px" placeholder="请输入图中验证码" v-model="userData.code" autocomplete="off" />
              <el-image :src="img" style="width: 80px;border-radius: 3px; height: 31px;left: 165px;top:2px;position: absolute" @click="refreshCaptcha" />
<!--              <el-button v-if="!flag" style="width: 80px;border-radius: 3px; height: 31px;left: 165px;top:2px;position: absolute" type="primary" link @click="getCode">获取验证码</el-button>-->
<!--              <el-button v-else style="width: 80px;border-radius: 3px; height: 31px;left: 165px;top:2px;position: absolute" type="primary" disabled link @click="getCode">{{time}}{{text}}</el-button>-->
            </div>
          </el-form-item>
          <el-form-item>
<!--            <el-button v-if="loginFlag" type="primary"  style="width: 245px" @click="submitForm(formRef)">登录</el-button>-->
            <el-button type="primary" :loading="loading"  style="width: 245px" @click="submitForm(formRef)">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.back-container {
  background-image: url("../../../assets/home-login-bg.jpg") ;
  /*no-repeat center center*/
  background-size: cover;
  height: 100vh;
}

.back-login-form {
  position: absolute;
  left: 60%;
  top: 40%;
  margin: -100px 0 0 -100px;
  background-color: white;
  width: 300px;
  height: 340px;
  display: flex;
  border-radius: 5px;
}
.back-login-form img{
  margin: 8px 0 0 90px;
  width: 120px;
  height: 100px;
  border-radius: 50%
}
.form{
  position: absolute;
  left: 43%;
  top: 70%;
  margin: -100px 0 0 -100px;
  /*text-align: center;*/
}

.code-form-item img {
  cursor: pointer;
}
</style>
